/**
 * advancedNews
 * @authors 杨兴洲（of2502）
 * @date    2017/5/17 0017 16:15
 * @version 1.0
 */
import {Router} from "express";
import logger from "../../util/logger";
import UserService from "../../service/user-service";
import AdvancedNewsService from "../../service/advancedNews-service";

const router = Router();


function checkNews(req, res, next) {
    const {articles} = req.body;
    if (!articles || !Array.isArray(articles) || articles.length < 1) {
        const error = new Error();
        error["errcode"] = 10902;
        error["errmsg"] = "articles不能为空";
        return next(error);
    }

    next();
}


function checkIDExist(req, res, next) {
    const {id} = req.body || req.query;
    if (!id) {
        const error = new Error();
        error["errcode"] = 10901;
        error["errmsg"] = "id不能为空";
        return next(error);
    }
    next();
}

/**
 * 获取高级图文列表
 */
router.get('/list', (req, res, next) => {
    (async () => {
        try {
            const {page, pageSize} = req.query;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);

            const result = await AdvancedNewsService.getList({appID, page, pageSize: +pageSize});
            logger.debug(JSON.stringify(result));
            res.status(200).json({
                item: result.list,
                item_count: result.list.length,
                total_count: result.total
            });
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 新建高级图文
 */
router.post('/create', [checkNews], (req, res, next) => {
    (async () => {
        try {
            const {articles} = req.body;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await AdvancedNewsService.createNews({appID, articles});
            logger.debug("新建高级图文", JSON.stringify(result));
            res.status(200).json({id: result._id});
        } catch (error) {
            next(error);
        }
    })();
});


// getDetail
router.get('/detail', (req, res, next) => {
    (async () => {
        try {
            const {id: newsID} = req.query;

            const result = await AdvancedNewsService.getDetail(newsID);
            if (!result) {
                return res.status(200).json({
                    errcode: 10903,
                    errmsg: "此高级图文不存在,可能已经被删除"
                });
            }
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});
/**
 * 更新高级图文
 */
router.post('/update', [checkIDExist], (req, res, next) => {
    (async () => {
        try {
            const {id: newsID, articles, index} = req.body;
            // const {userID} = res.locals;
            // const {authorizer_appid: appID} = await UserService.getInfo(userID);

            const result = await AdvancedNewsService.updateNews({newsID, articles, index});
            logger.debug("更新高级图文" + newsID, JSON.stringify(result));
            if (!result) {
                return res.status(200).json({
                    errcode: 10903,
                    errmsg: "此高级图文不存在,可能已经被删除"
                });
            }
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 删除高级图文
 */
router.post('/delete', [checkIDExist], (req, res, next) => {
    (async () => {
        try {
            const {id: newsID} = req.body;
            const {userID} = res.locals;
            // const {authorizer_appid: appID} = await UserService.getInfo(userID);


            let list = await UserService.getUsedAdNewsList(userID);
            if (list.indexOf(newsID) >= 0) {
                return res.status(200).json({
                    errcode: 10904,
                    errmsg: "此高级图文已被菜单使用,不能删除"
                });
            }

            const result = await AdvancedNewsService.deleteNews(newsID);
            logger.debug("删除高级图文" + newsID, JSON.stringify(result));
            if (!result) {
                return res.status(200).json({
                    errcode: 10903,
                    errmsg: "此高级图文不存在,可能已经被删除"
                });
            }
            res.status(200).json({
                errcode: 0,
                errmsg: "ok"
            });
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
